package com.smile.cn.bean;

import com.smile.cn.entity.MailAuthentication;
import com.sun.mail.imap.IMAPFolder;
import java.util.ArrayList;
import java.util.List;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;

public class DeleteEmailBean {
	/**
	 * delete the email by number
	 * 
	 * @param account
	 * @param id
	 * @throws Exception
	 */
	public void expungeMessage(MailAuthentication account, int id)
			throws Exception {
		GetFolderBean getFolder = new GetFolderBean();
		Folder folder = getFolder.getFolder(account);
		folder.open(2);
		Message msg = null;
		msg = folder.getMessage(id);
		msg.setFlag(Flags.Flag.DELETED, true);
		if ((folder != null) && (folder.isOpen())
				&& (!account.getUserName().contains("qq.com"))) {
			folder.close(true);
		} else if ((folder != null) && (folder.isOpen()))
			folder.close(false);
	}

	/**
	 * delete email by id
	 * 
	 * @param account
	 * @param uid
	 * @throws Exception
	 */
	public void expungeMessageByID(MailAuthentication account, String id)
			throws Exception {
		GetFolderBean getFolder = new GetFolderBean();
		Folder folder = getFolder.getFolder(account);
		IMAPFolder imapFolder = null;
		Message msg = null;
		String mailType = getFolder.getMailType();
		if ((mailType != null) && (mailType.equalsIgnoreCase("imap"))) {
			imapFolder = (IMAPFolder) folder;
			imapFolder.open(2);
			msg = imapFolder.getMessageByUID(Long.parseLong(id));
			msg.setFlag(Flags.Flag.DELETED, true);
			imapFolder.expunge();
			if ((imapFolder != null) && (imapFolder.isOpen()))
				imapFolder.forceClose();
		} else
			;
	}

	/**
	 * empty all the email box
	 * 
	 * @param account
	 * @throws Exception
	 */
	public void emptyFolder(MailAuthentication account) throws Exception {
		GetAllFolder getFolder = new GetAllFolder();
		List<String> folders = new ArrayList<String>();
		// folders.add("INBOX");
		// folders.add("INBOX.Sent");
		// folders.add("INBOX.Draft");
		// folders.add("INBOX.Trash");
		// folders.add("Wsubscribe");
		for (String folderName : folders) {
			Folder folder = getFolder.getEachFolder(account, folderName);
			IMAPFolder imapFolder = null;
			Message[] msgs = (Message[]) null;
			String mailType = getFolder.getMailType();
			if ((mailType != null) && (mailType.equalsIgnoreCase("imap"))) {
				imapFolder = (IMAPFolder) folder;
				imapFolder.open(2);
				msgs = imapFolder.getMessages();
				for (int i = 0; i < msgs.length; i++) {
					msgs[i].setFlag(Flags.Flag.DELETED, true);
				}
				imapFolder.expunge();
				if ((imapFolder != null) && (imapFolder.isOpen()))
					imapFolder.forceClose();
			}
		}
	}
}
